<!--  -->
<template>
  <div class="contianer" v-stream:scroll="scroll$">
    <Nav title="融媒优品">
      <template v-slot:left>
        <router-link tag="div" :to="{name:'position'}" class="flex position-address aligin-center">
          <span class>{{address}}</span>
          <span class="position-icon"></span>
        </router-link>
      </template>
    </Nav>
    <!-- <div class="position flex justify-between aligin-center">
      <div class="flex aligin-center">
        <span class="position-icon"></span>
        <span class="">{{address}}</span>
      </div>
      <router-link tag="span" :to="{name:'position'}" class="color-red">【切换城市】</router-link>
    </div>-->

    <!-- 轮播图 -->
    <swiper class="swiper mt-10" :options="swiperOption" v-if="swiperSlides.length!=0">
      <swiper-slide v-for="(slide, index) in swiperSlides" :key="index">
        <img :src="slide.adv_image" alt @click="bannerTo(slide.adv_url)" />
      </swiper-slide>
      <div class="swiper-pagination" slot="pagination"></div>
    </swiper>
    <div class="swiper mt-10" v-else></div>
    <!-- 中奖纪录 -->
    <!-- <div class="record-list flex aligin-center justify-between f-12">
      <span class="hot-icon flex aligin-center justify-center">热</span>
      <div class="ml-20 title f-bold">今日中奖:</div>
      <swiper class="ml-12 record-swiper" :options="recordOptionList" v-if="recordList.length!=0">
        <swiper-slide v-for="(item, index) in recordList" :key="index">
          <div class="f-medium swipe-item f-14">
            恭喜
            <span class="f-bold color-red ml-4 mr-4 ellipsis w-80">{{item.username}}</span>预购
            <span class="f-bold color-red ml-4 mr-4">{{item.numbers}}件</span>商品获得
            <span class="f-bold color-red ml-4 mr-4 ellipsis w-80">{{item.reward}}</span>
            奖励
          </div>
        </swiper-slide>
      </swiper>
      <span class="arrow-right mr-8 ml-24"></span>
    </div>-->
    <!-- 菜单9宫格 -->
    <div class="flex f-14">
      <router-link
        to="/shareReward"
        tag="div"
        class="menu-item flex flex-column aligin-center justify-center"
      >
        <span class="share"></span>
        <span class="mt-8 f-bold">分享有礼</span>
      </router-link>
      <router-link
        tag="div"
        class="menu-item flex flex-column aligin-center justify-center"
        :to="{name:'message'}"
      >
        <span class="strategy"></span>
        <span class="mt-8 f-bold">商城公告</span>
      </router-link>
      <router-link
        tag="div"
        :to="{name:'company-home'}"
        class="menu-item flex flex-column aligin-center justify-center"
      >
        <span class="hot-action"></span>
        <span class="mt-8 f-bold">兴兰助企</span>
      </router-link>
      <router-link
        to="/index/customerService"
        tag="div"
        class="menu-item flex flex-column aligin-center justify-center"
      >
        <span class="service"></span>
        <span class="mt-8 f-bold">在线客服</span>
      </router-link>
    </div>
    <div class="divide-line"></div>
    <div class="ads flex aligin-center justify-center" v-if="adList&&adList.length">
      <img class="ads-img" :src="adList[0].adv_image" alt @click="bannerTo(adList[0].adv_url)" />
    </div>
    <div class="divide-line"></div>
    <!-- tab选项 -->
    <div id="tab2"></div>
    <div class="flex justify-between aligin-center" :class="isSticky?'sticky':''">
      <div class="tab-container">
        <Scroll :scrollX="true">
          <TabCommon
            :type="2"
            :isScroll="true"
            id="tabEvent"
            :tabs.sync="tabs"
            :tabIndex.sync="tabIndex"
            v-stream:tabChange="tabChange$"
          ></TabCommon>
        </Scroll>
      </div>
      <span class="refresh" v-stream:click="refresh$"></span>
    </div>
    <div :class="isSticky?' pt-64':''" class="height-full">
      <div class="flex aligin-center justify-center" v-if="isRefesh">
        <van-loading color="#EA373F" />
      </div>
      <div class="flex justify-between aligin-start flex-wrap">
        <template v-for="(item,index) in observabelProductList">
          <div class="product-item" :key="index" @click="toRewordDetail(item)">
            <div
              class="peroid flex aligin-center justify-center color-white"
              v-if="item.show_issue"
            >第{{item.issue_id}}期</div>
            <img :src="item.image" alt />
            <div class="mt-8 ellipsis-line2 f-14 product-name">{{item.name}}</div>
            <div class="progress-wrapper mt-10">
              <div class="progress" :style="{width:item.progress+'%'}"></div>
            </div>
            <div class="flex mt-4 justify-between aligin-center f-12">
              <div class="color-red f-12">活动进度：{{item.current}}/{{item.power}}</div>
            </div>
            <div
              v-if="item.open_status"
              class="product-item-mask flex justify-center f-18 color-red"
            >
              <span
                class="tag color-white f-12 flex justify-center aligin-center"
              >{{item.open_status==1?'即将揭晓':'已揭晓'}}</span>
            </div>
          </div>
        </template>
        <div class="loading-bottom mt-10 f-14" v-if="loading">加载中...</div>
        <div class="loading-bottom mt-10 f-14" v-if="noMore">没有更多了</div>
      </div>
    </div>
    <Ads :adsInfo.sync="adsInfo" :adsFlag.sync="adsFlag" @closeAds="adsFlag=false"></Ads>
    <loginReward :count="count" :loginRewardFlag="loginRewardFlag" @closeAds="loginRewardFlag=false"></loginReward>
  </div>
</template>

<script>
import GuideDialog from '../../components/Guide.js'
import Nav from '../../components/Nav'
import Scroll from '../../components/Scroll'
import TabCommon from '../../components//TabCommon'
import { home, activities } from '../../api/api'
import Ads from '../../components/ads'
import Page from '../../mixin/page'
import Dialog from '../../components/positionDialog'
import loginReward from "../../components/loginReward"
import { fromEvent, from, merge, empty, of, concat } from 'rxjs'
import {
  map,
  filter,
  exhaustMap,
  debounceTime,
  switchMap,
  throttleTime,
  tap,
  concatMap
} from 'rxjs/operators'
export default {
  mixins: [Page],
  name: 'Home',
  components: {
    Nav,
    TabCommon,
    Ads,
    Scroll,
    loginReward
  },
  domStreams: ['tabChange$', 'refresh$',"scroll$"],
  data() {
    return {
      loginRewardFlag:false,
      f_req: '',
      count:0,
      adsInfo: {},
      adList: [{ adv_image: '' }], //广告数组
      adsFlag: false,
      swiperOption: {
        loop: true,
        autoplay: true, //等同于以下设置
        centeredSlides: true,
        slidesPerView: 'auto',
        spaceBetween: 7,
        pagination: {
          el: '.swiper-pagination'
        }
      }, //轮播图配置
      recordOptionList: {
        loop: true,
        direction: 'vertical',
        autoplay: true //等同于以下设置
      }, //广播消息配置
      recordList: [], //广播列表
      swiperSlides: [], //轮播图
      tabs: [],
      tabIndex: 0,
      productList: [],
      _tabList: [],
      isSticky: false
    }
  },
  subscriptions() {
    let subscribtion = this.initRxjs()
    return {
      observabelProductList: subscribtion
    }
  },
  computed: {
    address() {
      let { province = '', city = '', district = '' } =
        this.$store.state.location[0] || {}
      return province + city + district ? district : '定位有误，请重新定位'
    },
    getTabTop() {
      return document.getElementById('tab2').offsetTop
    }
  },
  methods: {
    bannerTo(url) {
      let _url = url.split('|')
      switch (_url[0]) {
        case 'HD':
          this.$router.push({ name: 'detail', params: { id: _url[1] } })
          break
        case 'XLZQ':
          this.$router.push({ name: 'company-home'})
          break
        case "BJ":
          this.$router.push({name:"discount"})
          break
        case 'FWB':
          this.$router.push({ 
            name: 'activities',
            params: { id: parseInt(_url[1]) }
          })
          break
        case 'FX':
          this.$router.push({ name: 'shareReward' })
          break
      }
    },
    tipDevelop() {
      this.$notify('该功能正在开发，敬请期待')
    },
    toAttendDetail(item) {
      this.$router.push({ name: 'joindetail', params: { key: item.key } })
    },
    _shareConfig(jsk) {
      let that = this
      wx.config(jsk)
      wx.ready(() => {
        wx.updateTimelineShareData({
          title: '融媒优品', // 分享标题
          link: window.location.origin + window.location.pathname, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: 'https://cdn.weile999.com/ygp_v2/logo/logo.png', // 分享图标
          success: function() {
            // 设置成功
          }
        })
        wx.updateAppMessageShareData({
          title: '融媒优品', // 分享标题
          link: window.location.origin + window.location.pathname, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          desc: '兰溪官方特色购物平台。', // 分享描述
          imgUrl: 'https://cdn.weile999.com/ygp_v2/logo/logo.png', // 分享图标
          success: function() {
            // 设置成功
          }
        })

        if (!this.$store.state.isHandle) {
          // wx.getLocation({
          //   type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          //   success: function(res) {
          //     var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          //     var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          //     var speed = res.speed; // 速度，以米/每秒计
          //     var accuracy = res.accuracy; // 位置精度
          //   },
          //   fail: function(res) {
          //     console.log("error start", res);
          //   }
          // });
        }
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
      })
      wx.error(res => {
        console.log("home error",res)
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
      })
    },
    //跳转奖励详情
    toRewordDetail(item) {
      this.$router.push({ name: 'detail', params: { id: item.id } })
    },
    initRxjs() {
      //滚动事件
      let scroll = this.scroll$.pipe(
        //判断吸顶
        tap(({event:{target}}) => {
          this.isSticky = target.scrollTop >= this.getTabTop
        }),
        //判断是否滚动到底部
        filter(({event:{target}}) => {
          return this.isScrollEnd(target)
        }),
        //判断是否还有数据未加载
        filter(this.noMoreData),
        filter(() => this.f_req),
        //截流
        throttleTime(500),
      )
      //tab 切换事件
      let tabEvent = this.tabChange$.pipe(
        //判断是否是有效切换
        filter(({ event: { msg: index } }) => {
          if (this.tabIndex != index) {
            this.f_req = this._tabList[index].alias
            this.tabIndex = index
            this.current_page = 0
            this.last_page = 1
            this.productList = []
            if (this.isSticky) {
              document.documentElement.scrollTop = this.getTabTop
              document.body.scrollTop = this.getTabTop
            }
            return true
          }
          return false
        })
      )
      //初始化 活动事件
      let initScroll = of(1).pipe(
        concatMap(() => home()),
        tap(({ data: { result } }) => {
          this.swiperSlides = result.banners
          this.recordList = result.broadcasts
          this.adList = result.ad
          this._tabList = result.tab
          this.f_req = result.f_req
          this.tabs = result.tab.map(item => item.name)
          // if (result.message) {
          //   if (this.$store.state.activityId != result.message.article_id) {
          //     this.adsInfo = result.message;
          //     this.adsFlag = true;
          //     this.$store.commit("saveID", result.message.article_id);
          //   }
          // }
          // 微信分享配置
          if (typeof wx != 'undefined') {
            this._shareConfig(result.jsk)
          }
          if(result.f_login&&result.login_state){
            this.loginRewardFlag=true
            this.count=result.c
          }
          let that = this
          if (!this.$store.state.isHandle) {
            AMap.plugin('AMap.Geolocation', function() {
              var geolocation = new AMap.Geolocation({
                // 是否使用高精度定位，默认：true
                enableHighAccuracy: true,
                // 设置定位超时时间，默认：无穷大
                timeout: 10000,
                // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
                buttonOffset: new AMap.Pixel(10, 20),
                //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                zoomToAccuracy: true,
                //  定位按钮的排放位置,  RB表示右下
                buttonPosition: 'RB'
              })

              geolocation.getCurrentPosition()
              AMap.event.addListener(geolocation, 'complete', onComplete)
              AMap.event.addListener(geolocation, 'error', onError)

              function onComplete(data) {
                // data是具体的定位信息
                console.log('position data', data)
                let { lng: longitude, lat: latitude } = data.position
                let {
                  addressComponent: { province, city, district }
                } = data
                let position = {
                  province,
                  city,
                  district,
                  longitude,
                  latitude
                }
                let {
                  province: old_province,
                  city: old_city,
                  district: old_district
                } = that.$store.state.location[0] || {}
                if (!old_province || !old_city || !old_district) {
                  that.$store.commit('saveLocation', position)
                  return
                }
                if (
                  old_province == province &&
                  old_city == city &&
                  old_district == district
                ) {
                  return
                }
                Dialog(old_district, () => {
                  that.$store.commit('saveLocation', position)
                })
              }

              function onError(data) {
                // 定位出错
                console.log('position error', data)
              }
            })
            // let { lng: longitude, lat: latitude } = map.getCenter();

            // AMap.plugin("AMap.Geocoder", function() {
            //   var geocoder = new AMap.Geocoder({
            //     // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
            //     city: "全国"
            //   });
            //   var lnglat = [longitude, latitude];
            //   geocoder.getAddress(lnglat, function(status, result) {
            //     if (status === "complete" && result.info === "OK") {
            //       // result为对应的地理位置详细信息
            //       console.log("result", result);
            //       let {
            //         regeocode: {
            //           addressComponent: { province, city, district }
            //         }
            //       } = result;
            //       let position = {
            //         province,
            //         city,
            //         district,
            //         longitude,
            //         latitude
            //       };
            //       let {
            //         province: old_province,
            //         city: old_city,
            //         district: old_district
            //       } = that.$store.state.location[0] || {};
            //       if (!old_province || !old_city || !old_district) {
            //         that.$store.commit("saveLocation", position);
            //         return;
            //       }
            //       if (
            //         old_province == province &&
            //         old_city == city &&
            //         old_district == district
            //       ) {
            //         return;
            //       }
            //       Dialog(old_district, () => {
            //         that.$store.commit("saveLocation", position);
            //       });
            //     }
            //   });
            // });
          }
        })
      )
      //刷新事件
      let refresh = this.refresh$.pipe(
        tap(() => {
          this.current_page = 0
          this.last_page = 1
          this.productList = []
        }),
        //防抖
        debounceTime(500)
      )
      return merge(initScroll, scroll, tabEvent, refresh).pipe(
        //替换
        switchMap(() =>
          activities({
            page: this.current_page + 1,
            type: this.f_req
          })
        ),
        map(this.execResult)
      )
    }
  },
  created() {},
  mounted() {
    // if (!this.$store.state.isLogin) {
    //   GuideDialog();
    // }
  },
  updated() {}, //生命周期 - 更新之后
  destroyed() {} //生命周期 - 销毁完成
}
</script>
<style lang='less' scoped>
@import url('../../assets/style/mixin.less');
//@import url(); 引入公共css类
// 修改swipe dot
.w-80 {
  max-width: 80px;
}
.contianer /deep/ .swiper-container {
  padding-bottom: 20px;
}
.record-list /deep/ .swiper-container {
  padding-bottom: 0;
}
.contianer /deep/ .swiper-pagination-fraction,
.swiper-pagination-custom,
.swiper-container-horizontal > .swiper-pagination-bullets {
  bottom: 0;
}
.contianer /deep/ .swiper-pagination-bullet {
  border-radius: 50%;
  width: 5px;
  height: 5px;
  background: #b6b6b7;
  transition: all 0.3s ease;
}
.contianer /deep/ .swiper-pagination-bullet-active {
  width: 23px;
  height: 5px;
  border-radius: 3px;
  .bg-1();
}
.contianer /deep/ .nav {
  position: relative;
  font-size: 12px;
  padding: 0 10px;
  justify-content: center;
}
.pt-64 {
  padding-top: 64px;
}
.height-full {
  // min-height: calc(100% - 64px);
}
.contianer {
  height: 100%;
  overflow-y: auto;
  .position-address {
    position: absolute;
    left: 9px;
    top: 50%;
    height: 13px;
    transform: translateY(-50%);
  }
  .position-icon {
    margin-top: 2px;
    margin-left: 2px;
    width: 16px;
    height: 11px;
    background: url('../../assets/imgs/arrow-down-b.png');
    background-size: 100% 100%;
  }
  .color-red {
    color: #f94d55;
  }

  .logo {
    margin: 0 auto;
    width: 53px;
    height: 15px;
    .bg-image('../../assets/imgs/logo');
    background-size: 100% 100%;
  }
  .msg {
    position: relative;
    display: inline-block;
    width: 17px;
    height: 16px;
    .bg-image('../../assets/imgs/msg');
    background-size: 100% 100%;
  }
  // 轮播图
  .swiper {
    height: 175px;
    .swiper-slide {
      margin-top: 5.5px;
      width: 90%;
      height: 164px;
      transition: height 0.3s ease, margin-top 0.3s ease;
    }
    .swiper-slide-active {
      margin-top: 0;
      height: 175px;
    }
    img {
      height: 100%;
      width: 100%;
      border-radius: 4px;
    }
  }
  // 中奖纪录
  .record-list {
    position: relative;
    margin: 15px 15px;
    padding: 8px 0;
    width: 90%;
    height: 46px;
    box-sizing: border-box;
    background: #f8f8f8;
    border-radius: 5px;
    .hot-icon {
      position: absolute;
      top: 0;
      left: 0;
      width: 18px;
      height: 18px;
      font-size: 10px;
      color: #f8f8f8;
      font-weight: 500;
      .bg-image('../../assets/imgs/hot-icon');
      background-size: 100% 100%;
    }
    .title {
      width: 60px;
      height: 100%;
    }
    .record-swiper {
      flex: 1;
      height: 35px;
    }
    .swipe-item {
      display: flex;
      height: 100%;
      line-height: 18px;
      text-align: center;
    }
    .arrow-right {
      width: 9px;
      height: 9px;
      .bg-image('../../assets/imgs/arrow-right');
      background-size: 100% 100%;
    }
  }
  // 九宫格菜单
  .menu-item {
    padding: 10px 0;
    width: 25%;
    .new-guide {
      height: 48px;
      width: 48px;
      background: url('../../assets/imgs/new-guide.png');
      background-size: 100% 100%;
    }
    .strategy {
      height: 48px;
      width: 48px;
      background: url('../../assets/imgs/strategy.png');
      background-size: 100% 100%;
    }
    .hot-action {
      height: 48px;
      width: 48px;
      background: url('../../assets/imgs/winner-share.png');
      background-size: 100% 100%;
    }
    .notify {
      height: 48px;
      width: 48px;
      background: url('../../assets/imgs/notify.png');
      background-size: 100% 100%;
    }
    .share {
      height: 48px;
      width: 48px;
      background: url('../../assets/imgs/share.png');
      background-size: 100% 100%;
    }
    .join {
      height: 48px;
      width: 48px;
      background: url('../../assets/imgs/join.png');
      background-size: 100% 100%;
    }
    .service {
      height: 48px;
      width: 48px;
      background: url('../../assets/imgs/service.png');
      background-size: 100% 100%;
    }
    .about {
      height: 48px;
      width: 48px;
      background: url('../../assets/imgs/about.png');
      background-size: 100% 100%;
    }
  }
  .ads {
    height: 99px;
    .ads-img {
      width: 346px;
      height: 88px;
    }
  }
  .sticky {
    position: fixed;
    top: 0;
    height: 64px;
    width: 100%;
    background: #fff;
    z-index: 100;
  }
  //tab common
  .tab-container {
    padding: 10px 10px;
    width: 80%;
    overflow: hidden;
  }
  .refresh {
    margin-right: 20px;
    height: 20px;
    width: 20px;
    background: url('../../assets/imgs/refresh.png');
    background-size: 100% 100%;
    transition: all 0.3s ease;
    &:active {
      transform: rotate(180deg);
    }
  }
  .flex-wrap {
    padding: 0 10px; 
    flex-wrap: wrap;
    box-sizing: border-box;
  }
  .aligin-start {
    align-items: flex-start;
  }
  .product-item {
    position: relative;
    width: 165px;
    box-sizing: border-box;
    &:nth-child(n + 3) {
      margin-top: 10px;
    }
    // &:nth-child(2n + 1) {
    //   margin-left: 10px;
    // }
    // &:nth-child(2n) {
    //   margin-right: 10px;
    // }
    img {
      display: block;
      width: 100%;
      height: 165px;
      border-radius: 5px;
    }
    .peroid {
      position: absolute;
      top: 0;
      left: 0;
      width: 60px;
      height: 23px;
      font-size: 11px;
      background: url('../../assets/imgs/peroid.png');
      background-size: 100% 100%;
    }
    .product-name {
      height: 32px;
      line-height: 16px;
    }
    .progress-wrapper {
      position: relative;
      height: 6px;
      background: #eee;
      border-radius: 3px;
    }
    .color-red {
      color: #eb484e;
    }
    .progress {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      border-radius: 3px;
      .bg-1();
    }
    .power {
      display: inline-block;
      width: 14px;
      height: 14px;
      .bg-image('../../assets/imgs/power');
      background-size: 100% 100%;
    }
    .receive-count {
      display: inline-block;
      width: 14px;
      height: 14px;
      .bg-image('../../assets/imgs/receive');
      background-size: 100% 100%;
    }
    .product-item-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: calc(100%);
      height: 100%;
      background: #fff;
      opacity: 0.8;
      align-items: flex-start;
    }
    .tag {
      opacity: 1;
      width: 69px;
      height: 24px;
      border-bottom-left-radius: 3px;
      border-bottom-right-radius: 3px;
      background: #ff6a6e;
    }
    // }
  }
  .loading-bottom {
    width: 100%;
    text-align: center;
  }
}
</style>